<div id="formDiv" style="height: 100%"></div>

<script type="text/html" id="formContent">
  <form lay-filter="exchangeRecordsForm" class="layui-form open-form" id="exchangeRecordsForm">
    <div class="open-model">
      <div class="open-auto">
        <input name="id" type="hidden" />
        <div class="layui-col-md4">
          <div class="layui-form-item">
            <label class="layui-form-label">{{d.typeNameData}}类型</label>
            <div class="layui-input-block">
              <select id="type" name="type" lay-filter="type"></select>
            </div>
          </div>
        </div>
        <div class="layui-col-md4">
          <div class="layui-form-item">
            <label class="layui-form-label">供应商名称</label>
            <div class="layui-input-block">
              <select id="supplierId" name="supplierId" lay-filter="supplierId"></select>
            </div>
          </div>
        </div>
        <div class="layui-col-md4">
          <div class="layui-form-item">
            <label class="layui-form-label">运单编号</label>
            <div class="layui-input-block">
              <select id="waybillNo" name="waybillNo" lay-filter="waybillNo"></select>
            </div>
          </div>
        </div>
        <div class="layui-col-md4">
          <div class="layui-form-item">
            <label class="layui-form-label">关联订单编号</label>
            <div class="layui-input-block">
              <input id="purOrderCode" class="layui-input adv-disable" type="text" name="purOrderCode" disabled />
              <input id="purOrderId" class="layui-input" type="hidden" name="purOrderId" />
            </div>
          </div>
        </div>
        <div class="layui-col-md4">
          <div class="layui-form-item">
            <label class="layui-form-label">{{d.typeNameData}}备注</label>
            <div class="layui-input-block">
              <input name="remark" id="remark" class="layui-input" type="text" />
            </div>
          </div>
        </div>
        <!-- {{# if(d.eventName=='sendFun'||d.eventName=='getFun'){ }} -->
        <div id="addLogisticsInfoDiv">
          <div class="layui-col-md4">
            <div class="layui-form-item">
              <label class="layui-form-label">发货方式</label>
              <div class="layui-input-block">
                <select id="returnType" name="returnType" lay-filter="returnType"></select>
              </div>
            </div>
          </div>
          <div class="layui-col-md4">
            <div class="layui-form-item">
              <label class="layui-form-label">物流公司</label>
              <div class="layui-input-block">
                <input name="logisticsCompany" id="logisticsCompany" class="layui-input" type="text" />
              </div>
            </div>
          </div>
          <div class="layui-col-md4">
            <div class="layui-form-item">
              <label class="layui-form-label">{{d.typeNameData}}运单号</label>
              <div class="layui-input-block">
                <input name="waybillNumber" class="layui-input" type="text" />
              </div>
            </div>
          </div>
          <div class="layui-col-md4">
            <div class="layui-form-item">
              <label class="layui-form-label">车牌号</label>
              <div class="layui-input-block">
                <input name="busNumber" class="layui-input" type="text" />
              </div>
            </div>
          </div>
        </div>
        <!-- {{# } }} -->
        <div class="layui-form-item">
          <button class="layui-btn" id="ConfigureItem">配置物料信息</button>
        </div>
        <table class="layui-table" lay-filter="formTable" id="formTable"></table>
      </div>
      <div class="layui-form-item text-right">
        <div class="right-btn">
          <button class="layui-btn layui-btn-primary " type="button" ew-event="closeDialog">关闭</button>
          <button class="layui-btn" lay-filter="productDetailSubmit" lay-submit>提交</button>
        </div>
      </div>
    </div>
  </form>
</script>

<script>
  layui.use(['layer', 'form', 'table', 'admin', 'upload', 'tree', 'laytpl'], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    var laytpl = layui.laytpl;
    // const parentData=JSON.parse(JSON.stringify(parentData.data))
    const nowData = { ...parentData };
    data = parentData.data ? { ...parentData.data } : '';
    form.render('select');

    laytpl(formContent.innerHTML).render({ ...nowData }, function (html) {
      $('#formDiv').html(html);
    });
    if (nowData.eventName == 'detail') {
      admin.setFormDisable('#exchangeRecordsForm', true);
    } else if (nowData.eventName == 'getFun' || nowData.eventName == 'sendFun') {
      admin.setFormDisable('#exchangeRecordsForm', true, '#addLogisticsInfoDiv');
    }
    table.render({
      elem: '#formTable',
      data: [],
      page: true,
      cols: [
        [
          { type: 'numbers', title: '序号', fixed: 'left' },
          { field: 'skuCode', title: '产品编号' },
          { field: 'skuSpec', title: '规格码' },
          { field: 'skuName', title: '产品名称' },
          { field: 'mainUnitName', title: '计价单位' },
          {
            field: 'mainQuantity',
            title: `${nowData.typeNameData}数量`,
            templet: admin.setTableInput('mainQuantity', ['detail', 'sendFun', 'getFun'].includes(nowData.eventName), 'mainQuantity'),
          },
          { field: 'submitTime', title: '辅助单位数', sort: true },
          {
            field: 'unitPrice',
            title: '单价',
            templet: admin.setTableInput('unitPrice', ['detail', 'sendFun', 'getFun'].includes(nowData.eventName), 'unitPrice'),
          },
          {
            field: 'totalPrice',
            title: '总价',
            templet: admin.setTableInput('totalPrice', true, 'totalPrice'),
          },
          {
            field: 'realSendQuantity',
            title: '发货数量',
            hide: !['sendFun', 'getFun'].includes(nowData.eventName),
            templet: admin.setTableInput('realSendQuantity', ['detail'].includes(nowData.eventName), 'mainQuantity'),
          },
          {
            field: 'remark',
            title: '备注',
            templet: admin.setTableInput('remark', ['detail', 'sendFun', 'getFun'].includes(nowData.eventName), 'remark'),
          },
        ],
      ],
      done: function (data) {
        admin.tableInputChange('formTable');
        admin.tableInputChangeByClass('formTable', 'mainQuantity', (index, value, tableData, field, tableId) => {
          let unitPrice = tableData[index].unitPrice;
          let totalPrice = (unitPrice * value).toFixed(2);
          tableData[index].totalPrice = totalPrice;
          admin.setTableColHtml(tableId, index, 'totalPrice', totalPrice);
        });
        admin.tableInputChangeByClass('formTable', 'realSendQuantity', (index, value, tableData, field, tableId) => {
          let unitPrice = tableData[index].unitPrice;
          let totalPrice = (value * unitPrice).toFixed(2);
          tableData[index].totalPrice = totalPrice;
          admin.setTableColHtml(tableId, index, 'totalPrice', totalPrice);
        });
      },
    });
    await admin.initDataSelectPro(nowData.selectTypeSrc, {}, 'type', `${nowData.typeNameData}类型`);
    await admin.initDataSelectPro(
      'enterprise/purchase/admin/supplierInfoPass/list',
      {},
      'supplierId',
      `供应商名称`,
      async (d) => {
        $('#purOrderId').val('');
        $('#purOrderCode').val('');
        await admin.initDataSelectPro(
          'enterprise/purchase/admin/purchaseDeliveryRecord/getWaybillInfoBy',
          { supplierId: d.value },
          'waybillNo',
          '运单编号',
          (d, obj) => {
            $('#purOrderId').val(obj?.purOrderId);
            $('#purOrderCode').val(obj?.purOrderCode);
            table.reload('formTable', {
              data: [], // 设置新的数据
            });
          },
          'waybillNo',
        );
      },
      'corporateName',
    );
    await admin.getDictListPro('returnType', 'return_method', `发货方式`);
    if (data.supplierId) {
      await admin.initDataSelectPro('enterprise/purchase/admin/purchaseDeliveryRecord/getWaybillInfoBy', { supplierId: data.supplierId }, 'waybillNo', '运单编号', (d, obj) => {}, 'waybillNo');
    }
    if (data.id) {
      if (nowData.typeNameData == '退货') {
        table.reload('formTable', { data: data.purReturnRecordDetails });
      } else {
        table.reload('formTable', { data: data.purBarterRecordDetails });
      }
      form.val('exchangeRecordsForm', data);
      // admin.initDataSelect(nowData.selectTypeSrc, {}, 'type', data.type, `${nowData.typeNameData}类型`)
      // admin.getDictList('supplierMethod', 'transport_mode', data.supplierMethod ? data.supplierMethod : '', `发货方式`)
      //   admin.getDictList('method', 'return_method', data.method, `${nowData.typeNameData}方式`)
      // admin.req('enterprise/purchase/admin/supplierInfoPass/list', {}, function (res) {
      //     admin.initDataSelect(res.data, {}, 'supplierId', data.supplierId, '供应商名称', 'corporateName',)
      //     admin.req('enterprise/purchase/admin/purchaseDeliveryRecord/getWaybillInfoBy', {
      //         supplierId: data.supplierId
      //     }, function (res1) {
      //         const list1 = res1.data
      //         $('#waybillNo').empty()
      //         admin.initDataSelect(list1, {}, 'waybillNo', data.waybillNo, '运单编号', 'waybillNo',)
      //         const value1 = list1.find(v => v.snID == data.snID)
      //         $('#snID').val(value1?.snID)
      //         $('#sn').val(value1?.sn)
      //         $('#ImgDIv').attr('src', data.fileUrl).show(); // Show image preview
      //         if (nowData.typeNameData == '退货') {
      //             table.reload('formTable', {data: data.purReturnRecordDetails})
      //             data.purReturnRecordDetails.forEach(v => {
      //                 $(`input[name='mainQuantity${v.id}']`).val(v['mainQuantity'])
      //                 $(`input[name='unitPrice${v.id}']`).val(v['unitPrice'])
      //                 $(`#totalPrice${v.id}`).text(v['totalPrice'])
      //                 $(`#remarkTable${v.id}`).val(v['remark'])
      //             })
      //         } else {
      //             table.reload('formTable', {data: data.purBarterRecordDetails})
      //             data.purBarterRecordDetails.forEach(v => {
      //                 $(`input[name='mainQuantity${v.id}']`).val(v['mainQuantity'])
      //                 $(`input[name='unitPrice${v.id}']`).val(v['unitPrice'])
      //                 $(`#totalPrice${v.id}`).text(v['totalPrice'])
      //                 $(`#remarkTable${v.id}`).val(v['remark'])
      //             })
      //         }
      //
      //         form.val('exchangeRecordsForm', data)
      //     })
      // })
    } else {
    }

    $('#ConfigureItem').click(function () {
      const id = $('#waybillNo').val();
      if (id) {
        admin.formOpen({
          area: '1200px',
          offset: '65px',
          title: '配置物料信息',
          path: 'components/purchase/returnRecord/itemTable.html',
          success: function () {
            parentData.id = id;
          },
          end: function () {
            const newData = childData.list;
            table.reload('formTable', {
              data: newData, // 设置新的数据
            });
          },
        });
      } else {
        layer.msg('请选择运单编号');
      }
      return false;
    });
    // 表单提交事件
    form.on('submit(productDetailSubmit)', function (d) {
      let formData = { ...d.field };
      if (nowData.typeNameData == '退货') {
        formData.purReturnRecordDetails = table.cache['formTable'].map((v) => {
          if (!v.purchaseDeliveryRecordDetailId) {
            v.purchaseDeliveryRecordDetailId = v.purchaseOrderDetailId;
          }
          return v;
        });
      } else {
        formData.purBarterRecordDetails = table.cache['formTable'].map((v) => {
          if (!v.purchaseDeliveryRecordDetailId) {
            v.purchaseDeliveryRecordDetailId = v.purchaseOrderDetailId;
          }
          return v;
        });
      }
      formData.buttonType = data.buttonType;
      formData.typeCode = 'FHJL';
      if (nowData) console.log('formData', formData);
      if (nowData.eventName === 'add' || nowData.eventName === 'edit') {
        admin.req(
          nowData.eventName === 'add' ? nowData.addUrl : nowData.editUrl,
          JSON.stringify(formData),
          function (res) {
            if (res.code == 200) {
              layer.closeAll();
              table.reload('tableDiv');
            } else {
              layer.msg(res.msg);
            }
          },
          nowData.eventName === 'add' ? 'POST' : 'PUT',
          true,
          'application/json; charset=utf-8',
        );
      } else if (nowData.eventName === 'sendFun') {
        formData.goodType = 2;
        formData.moduleType = nowData.typeNameData === '退货' ? 1 : 2;
        formData.recordId = nowData.data.id;
        delete formData.waybillNo;
        formData.details = formData.purReturnRecordDetails.map((v) => {
          return {
            recordDetailId: v.id,
            totalPrice: v.totalPrice,
            realSendQuantity: v.realSendQuantity,
            remark: v.remark,
          };
        });
        admin.req(
          nowData.addLogisticsInfo,
          JSON.stringify(formData),
          function (res) {
            if (res.code == 200) {
              layer.closeAll();
              table.reload('tableDiv');
            } else {
              layer.msg(res.msg);
            }
          },
          'POST',
          true,
          'application/json; charset=utf-8',
        );
      }
      //   admin.req(
      //       formData.id ? nowData.typeUrl + "/update" : nowData.typeUrl + "/add",
      //       JSON.stringify(formData),
      //       function (res) {
      //           if (res.code == 200) {
      //               layer.closeAll();
      //               table.reload("tableDiv");
      //           } else {
      //               layer.msg(res.msg);
      //           }
      //       },
      //       formData.id ? "PUT" : "POST",
      //       true,
      //       "application/json; charset=utf-8"
      //   );
      console.log('data', formData);
      return false;
    });

    function handleInputChange(d) {
      console.log(123, d);
    }

    imgUpload();

    function imgUpload() {
      upload.render({
        elem: '#productPicBtn1',
        url: config.upload_url + 'uploadFile',
        accept: 'file',
        headers: { Authorization: 'Bearer ' + config.getToken() },
        // acceptMime: 'image/*',
        exts: 'jpg|jpeg|png|gif',
        done: function (res) {
          // On successful upload
          if (res.code === 200) {
            $('#fileUrl').val(res.data.url); // Store the image URL in hidden input
            $('#fileName').val(res.data.fileName); // Store the image URL in hidden input
            $('#ImgDIv').attr('src', res.data.url).show(); // Show image preview
            layer.msg('图片上传成功');
          } else {
            layer.msg('图片上传失败: ' + res.msg);
          }
        },
        error: function () {
          // On upload failure
          layer.msg('上传失败，请重试');
        },
      });
    }
  });
</script>

<style>
  #exchangeRecordsForm .layui-form-label {
    width: 100px;
  }

  #exchangeRecordsForm .layui-input-block {
    margin-left: 130px;
  }

  #exchangeRecordsForm .layui-input-inline {
    margin-bottom: 15px;
  }
</style>
